package com.example.healkep;

import static com.example.healkep.utils.MD5.MD5Encode;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.healkep.bean.globalUserInfo;
import com.example.healkep.databinding.ActivityLoginBinding;
import com.example.healkep.utils.login.LoginViewModel;
import com.example.healkep.utils.login.LoginViewModelFactory;
public class LoginActivity extends AppCompatActivity {

    private static String user;
    private static int id;
    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;
    public static String sessionID;
    public static String url = "http://47.93.0.194:6666";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final Button loginButton = binding.login;
        final ProgressBar loadingProgressBar = binding.loading;
        final CheckBox checkBox = binding.checkBox;
        final TextView xieyiTv = binding.xieyiTv;
        final Button config = binding.config;
        config.setOnClickListener((view)->{
            EditText edit = new EditText(this);
            edit.setText(url);
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setView(edit)
                    .setNegativeButton("取消",null)
                    .setPositiveButton("确认", (d,which)->{
                        url = edit.getText().toString();
                    })
                    .setTitle("输入服务器IP及其对应的端口")
                    .create();
            dialog.show();
        });
        TextView registerButton = findViewById(R.id.button2);

        registerButton.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });

        loginViewModel.getLoginFormState().observe(this, loginFormState -> {
            if (loginFormState == null) {
                return;
            }
            loginButton.setEnabled(loginFormState.isDataValid());
            if (loginFormState.getUsernameError() != null) {
                usernameEditText.setError(getString(loginFormState.getUsernameError()));
            }
            if (loginFormState.getPasswordError() != null) {
                passwordEditText.setError(getString(loginFormState.getPasswordError()));
            }
        });

        loginViewModel.getLoginResult().observe(this, loginResult -> {
            if (loginResult == null) {
                return;
            }
            loadingProgressBar.setVisibility(View.GONE);
            if (loginResult.getError() != null) {
                showLoginFailed(loginResult.getError());
            }
            setResult(Activity.RESULT_OK);
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
            return false;
        });

        xieyiTv.setOnClickListener(view -> {
            WebViewActivity.startActivity(getApplicationContext(), "https://www.baidu.com/");
        });

        loginButton.setOnClickListener(v -> {

            if (!checkBox.isChecked()) {
                Toast.makeText(getApplicationContext(), "请阅读用户协议并勾选确认", Toast.LENGTH_SHORT).show();
                return;
            }

            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.login(usernameEditText.getText().toString(),
                    passwordEditText.getText().toString());
            String username = usernameEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            password = MD5Encode(password);
            String finalPassword = password;
            String json = "{\n" +
                    "    \"username\":\"" + username + "\",\n" +
                    "    \"password\":\"" + finalPassword + "\"\n" +
                    "}";
            Intent intent = new Intent(LoginActivity.this, CaptchaLActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("json",json);
            bundle.putString("username",username);
            intent.putExtras(bundle);
            startActivity(intent);
        });
    }

    private int getrole(String temp) {
        if (temp.equals("1")) {
            return 1;
        } else {
            return 0;
        }
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    public static int getId() {
        return id;
    }

    public static void setId(int id) {
        LoginActivity.id = id;
    }

    public static String getUser() {
        globalUserInfo info = globalUserInfo.getInstance();
        return info.getUsername();
    }

    public static String getSessionID() {
        return sessionID;
    }

    public static void setUser(String user) {
        globalUserInfo info = globalUserInfo.getInstance();
        info.setUsername(user);
        LoginActivity.user = user;
    }

    public static void setSessionID(String sessionID) {
        LoginActivity.sessionID = sessionID;
    }

}